// 获取弹窗和按钮元素
const showAddFormBtn = document.getElementById('showAddFormBtn');
const addHikeModal = document.getElementById('addHikeModal');
const closeModalBtn = document.getElementById('closeModalBtn');
const cancelAddFormBtn = document.getElementById('cancelAddFormBtn');

// 显示消息的函数 (优化版)
function displayMessage(message, isError = false) {
    if (!message) return; // 空消息不显示

    // 先尝试使用现有的消息系统
    if (isError) {
        showErrorMessage(message);
    } else {
        showSuccessMessage(message);
    }

    // 同时在消息显示区域显示 (如果有)
    const messageElement = document.getElementById('messageDisplay');
    if (messageElement) {
        messageElement.textContent = message;
        messageElement.style.color = isError ? 'red' : 'green';
        messageElement.style.display = 'block';

        // 3秒后自动消失
        setTimeout(() => {
            messageElement.style.display = 'none';
        }, 3000);
    }
        // 如果没有messageDisplay元素，确保至少alert系统会显示
    console.log('Display message:', message, isError ? '(error)' : '(success)');
}


// 显示/隐藏模态框函数
function showModal() {
    // 先检查用户是否还能添加数据
    checkAddDataLimit().then(canAdd => {
        if (canAdd) {
            addHikeModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
            setTimeout(() => {
                addHikeModal.classList.add('active');
            }, 10);
        } else {
            // 只有在不能添加时才显示消息
            displayMessage('您今天已达到添加数据的最大限制', true);
        }
    }).catch(error => {
        console.error('检查添加限制时出错:', error);
        displayMessage('无法检查添加限制，请稍后再试', true);
    });
}

// 检查添加数据限制的函数
async function checkAddDataLimit() {
    try {
        const response = await fetch('/check_add_limit', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'include'
        });

        if (!response.ok) {
            // 如果是403错误，表示用户已达到添加限制
            if (response.status === 403) {
                const result = await response.json();
                // 这里只返回false，不显示消息，由调用方决定是否显示
                return false;
            }
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
            // 更新计数器显示
            const counterElement = document.querySelector('.add-data-counter');
            if (counterElement) {
                counterElement.textContent = result.message ||
                    (result.remaining === '无限制' ? '管理员无限制' : `今日还可添加 ${result.remaining} 条数据`);
            }
            return result.can_add;
        } else {
            // 这里也不直接显示消息，由调用方处理
            return false;
        }
    } catch (error) {
        console.error('检查添加限制出错:', error);
        return false;
    }
}


function closeModal() {
    addHikeModal.classList.remove('active');
    document.body.style.overflow = ''; // 恢复背景滚动
    setTimeout(() => {
        addHikeModal.style.display = 'none';
    }, 300);
}

// 点击"添加数据"按钮显示弹窗
showAddFormBtn.addEventListener('click', showModal);

// 点击关闭按钮隐藏弹窗
closeModalBtn.addEventListener('click', closeModal);
cancelAddFormBtn.addEventListener('click', closeModal);

// 点击弹窗外部区域隐藏弹窗
addHikeModal.addEventListener('click', (event) => {
    if (event.target === addHikeModal) {
        closeModal();
    }
});

// 显示选中的文件名
document.getElementById('image').addEventListener('change', function(e) {
    const fileName = e.target.files[0] ? e.target.files[0].name : '选择图片文件';
    document.getElementById('file-name').textContent = fileName;
});

// 错误消息关闭
document.querySelectorAll('.error-close-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        this.closest('.error-message').classList.remove('active');
    });
});


// 表单提交处理
document.getElementById('addHikeForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    // 清空之前的消息
    const nameError = document.getElementById('nameError');
    if (nameError) nameError.classList.remove('active');
    displayMessage(''); // 清空消息

    const formData = new FormData(this);
    const submitBtn = this.querySelector('.submit-btn');

    // 禁用提交按钮防止重复提交
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span>提交中...</span>';

    try {
        const response = await fetch('/add_hike', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (response.status === 201) {
            // 添加成功
            displayMessage(result.message || '路线添加成功！');

            // 更新剩余添加次数显示
            if (result.remaining !== undefined) {
                const counterElement = document.querySelector('.add-data-counter');
                if (counterElement) {
                    counterElement.textContent = result.message || `今日还可添加 ${result.remaining} 条数据`;
                }
            }

            // 延迟刷新页面，让用户看到消息
            setTimeout(() => {
                closeModal();
                this.reset();
                window.location.reload();
            }, 2000);

        } else if (response.status === 400 && result.error === '徒步路线已存在') {
            // 显示名称已存在错误
            document.getElementById('nameError').classList.add('active');
            displayMessage('路线名称已存在', true);
        } else if (response.status === 403 && result.error === '达到添加限制') {
            // 这里不再显示消息，因为已经在showModal中显示过了
            closeModal();
        } else {
            // 其他错误
            displayMessage(result.error || '添加路线失败', true);
        }
    } catch (error) {
        console.error('Error:', error);
        displayMessage('网络错误，请重试', true);
    } finally {
        // 重新启用提交按钮
        submitBtn.disabled = false;
        submitBtn.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                <polyline points="17 21 17 13 7 13 7 21"></polyline>
                <polyline points="7 3 7 8 15 8"></polyline>
            </svg>
            <span>添加路线</span>
        `;
    }
});

// 显示成功消息
function showSuccessMessage(message) {
    const alertBox = document.createElement('div');
    alertBox.className = 'alert-message success';
    alertBox.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
            <polyline points="22 4 12 14.01 9 11.01"></polyline>
        </svg>
        <span>${message}</span>
    `;

    document.body.appendChild(alertBox);
    setTimeout(() => {
        alertBox.classList.add('show');
    }, 10);

    setTimeout(() => {
        alertBox.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(alertBox);
        }, 300);
    }, 3000);
}

// 显示错误消息
function showErrorMessage(message) {
    const alertBox = document.createElement('div');
    alertBox.className = 'alert-message error';
    alertBox.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="8" x2="12" y2="12"></line>
            <line x1="12" y1="16" x2="12.01" y2="16"></line>
        </svg>
        <span>${message}</span>
    `;

    document.body.appendChild(alertBox);
    setTimeout(() => {
        alertBox.classList.add('show');
    }, 10);

    setTimeout(() => {
        alertBox.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(alertBox);
        }, 300);
    }, 3000);
}

// 添加CSS样式到head
const style = document.createElement('style');
style.textContent = `
.alert-message {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    padding: 12px 24px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.95rem;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 1100;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.alert-message.show {
    opacity: 1;
    visibility: visible;
    transform: translateX(-50%) translateY(-10px);
}

.alert-message.success {
    background-color: rgba(46, 196, 182, 0.9);
    color: white;
}

.alert-message.error {
    background-color: rgba(239, 35, 60, 0.9);
    color: white;
}

.alert-message svg {
    width: 18px;
    height: 18px;
}
`;
document.head.appendChild(style);


document.addEventListener('DOMContentLoaded', () => {
    // 如果是普通用户，初始化检查限制
    if (document.querySelector('.add-data-counter')) {
        checkAddDataLimit().catch(error => {
            console.error('初始化检查限制失败:', error);
        });
    }
});